<?php
namespace Home\Controller;

use Vendor\Page;

class IndexController extends ComController
{
      public function _initialize()
      {
          parent::_initialize();

      }


    public function test1(){
        header("Content-Type: text/html; charset=UTF-8");


//        $chapter = D("novel_chapter")->field('id,chapter,title')->where('chapter is not null')->limit(0,10)->select();
        $sql = "select id,chapter,title from qw_novel_chapter where chapter is null limit 0,1000";
        $chapter = D("novel_chapter")->query($sql);
        for( $i = 0; $i < count($chapter); $i++ ){
            $chstr = $chapter[$i]["title"];
            if( $chapter[$i]["chapter"] == null ){
                if( $chapter[$i]["id"] == '' ){
                    continue;
                }
//                $str1 = strstr( $chstr, " ", true );
//                $strpos = strpos( $chstr, " " );
//                $str2 = substr($chstr,$strpos+3);
//                $str2 = trim( $str2 );
                $str1 = substr($chstr,0,5);
                $str2 = substr($chstr,5);

                $str1 = trim( $str1 );
                $str2 = trim( $str2 );


                $chapter[$i]['title'] = $str2;
                $chapter[$i]['chapter'] = $str1;
                $sql = "update qw_novel_chapter set title = '".$str2."',chapter = '".$str1."' where id = '".$chapter[$i]['id']."';";
                echo $sql;
                echo "<br/>";
            }else{
//                echo "不为空";
            }
        }

    }



    public function index()
    {
        $this->is_session();
//        echo __FILE__;
//        echo "<br/>";
//        echo __LINE__;
//        die();
//        echo "<meta charset='utf-8'>";
        $open_id = $_SESSION['user']['open_id'];
        //根据open_id查找出分类 然后智能推荐给用户付费最高的小说
        $continue_novel1 = json_decode(curl_request('http://bfvnu.cn/Home/api/getindexlunbo'),true);
        //$continue_novel1 = '';
        /*if(!empty($continue_novel1)){
//            第一本小说
            $continue_novel = array_shift($continue_novel1);
        }else{
            //获得轮播小说 第一本小说
            $continue_novel = D('novel')->where('is_shelf = 1')->field('id,img,mini_img')->order('flow_set asc')->limit(0,1)->find();
            //其他四本小说
            $continue_novel1 = D('novel')->where('is_shelf = 1')->field('id,img,mini_img')->order('flow_set asc')->limit(1,4)->select();
        }*/
        $map1['id'] = 650098876;

        $map2['id'] = array('in','65005406,650015550,65008951');
        $continue_novel = D('novel')->where('is_shelf = 1')->field('id,img,name,SUBSTRING(description,1,74) as description')->where($map1)->find();
//        echo D('novel')->getLastSql();
//        die();
        $continue_novel1 = D('novel')->where('is_shelf = 1')->field('id,img,name,substring(description,1,74) as description')->where($map2)->select();
//        echo D('novel')->getLastSql();
//        echo "<br/>";
//        echo "<br/>";
//        print_r($continue_novel1);
//        die();

        //dump($continue_novel);dump($continue_novel1);die;



        $this->assign('continue_novel', $continue_novel);
        $this->assign('continue_novel1', $continue_novel1);

        //随意挑选两部小说
        $rand = D('novel')->where('is_shelf = 1')->field('id,name,writer,description,img,mini_img')->order('rand()')->where("writer != ''")->limit(2)->select();
        //dump($xianshi_arr);die;
        $this->assign('rand',$rand);

        //主编推荐
        $recommendlist = D('novel')->where('is_shelf = 1')->field('id,img,mini_img,name')->order('order_set asc')->limit(9)->select();
        foreach($recommendlist as $key=>$item){
            if($key==0 || $key==1 || $key==2){
                $recommendlis[0][] = $item;
            }else{
                $recommendlis[1][] = $item;
            }
        }

        $this->assign('recommendlist',$recommendlis);

        //热门小说
        $is_hot_arr = D('novel')->field('id,name,description,writer,img,mini_img')->where('is_flag=1 and is_shelf = 1')->limit(3)->select();
        $this->assign('is_hot',$is_hot_arr);

        //获得最新的限时免费活动
        $activity = D('activity')->field('id,end_time')->where('status = 1 and type=1 ')->order('id desc')->find();
        $activity_id = $activity['id'];
        //$end_time = strtotime($activity['end_time']);
//    	$this->assign('end_year',date('Y', $end_time));
//    	$this->assign('end_month',date('m', $end_time));
//    	$this->assign('end_day',date('d', $end_time));
        //获得限免的小说
        if(!empty($activity_id)) {
            $list = D('novel')->field("id,name,img")->where("activity_id = $activity_id")->limit(3)->select();
            foreach($list as $key=>$item) {
                $list[$key]["is_free"] = 1;
                $list[$key]["start_time"] = $activity["start_time"];
                $list[$key]["end_time"] = $activity["end_time"];
                $ids[] = $item['id'];
            }
            $time = $list[0]['end_time'];
            $time = str_replace('-','/',$time);
            $this->assign('daojishi',$time);
            $this->assign('free_novel_list', $list);
        }
        else{
            $this->assign('free_novel_list', 0);
        }
        //print_r($free_novel_list);die;
        //print_r($free_novel_list);die;

        //最新推出的小说
        $newest_novel = D('novel')->order('id desc')->where('is_shelf = 1')->limit('0,3')->select();
        $this->assign('newest_novel', $newest_novel);

        //推送二维码送书币活动
        //查询在活动期间内的返回的钱
//        $time = date('Y-m-d',time());
//        $send_arr = D('activity')->where("type=2 and status=1 and start_time <= '$time' and end_time>='$time'")->find();
        //dump($send_arr);die;

        //$open_id = $_SESSION['user']['open_id'];

        //dump($_SESSION);die;
        if(!empty($open_id)){
            $subscribe_arr = D('user')->where("open_id='$open_id'")->find();
            $this->assign('subscribe_arr', $subscribe_arr);
        }

        //查出推荐的小说内容
        $Recommend = M('today_recommend'); // 实例化User对象
        // 查找status值为1name值为think的用户数据
        $data = $Recommend->select();

        //查找历史记录
        //查找支付路径
        $pay_path = D('pay_path')->field('pay_path')->where('status=1')->find();
        //畅销书单
        $changxiao1 = D('novel')->field('name,writer,id')->order('click_count desc')->limit(0,3)->select();
        $changxiao2 = D('novel')->field('name,writer,id')->order('click_count desc')->limit(3,3)->select();
        $this->assign('changxiao1',$changxiao1);
        $this->assign('changxiao2',$changxiao2);
        //最近阅读
        if(!empty($_SESSION['user'])){
            $map['open_id'] = $_SESSION['user']['open_id'];
            $history = D('read_history')->order('addtime desc')->where($map)->limit(3)->select();
            foreach($history as $key=>$vv){
                $id = $vv['novel_id'];
                $novel = D('novel')->field('img,description,writer,name')->where("id = $id")->find();
                $img = $novel['img'];
                $history[$key]['name'] = $novel['name'];
                $history[$key]['description'] = $novel['description'];
                $history[$key]['img'] = $img;
            }
            //dump($history);die;
            $this->assign('domain', $_SERVER['HTTP_HOST']);
            $this->assign('history', $history);
        }else{
            $history = '';
            $this->assign('domain', $_SERVER['HTTP_HOST']);
            $this->assign('history', $history);
        }

        //支付链接
        $pay = D('pay_path')->field('pay_path')->where('status = 1')->find();
        $this->assign('pay',$pay['pay_path']);
        $this->assign('back_domain', $_SERVER['HTTP_HOST']);

        $this->assign('recommend',$data);
        //$this->assign('send', $send_arr);
        $this->assign('open_id', $open_id);
        $this->assign('pay_path', $pay_path['pay_path']);


        $this->display();
    }


    /**
     * 猜你喜欢
     */
    public function love(){
        $rows = D('novel')->where('is_shelf = 1')->order('rand()')->limit(6)->select();
        $file_host = C('FILE_HOST_PATH');
        $data = [];
        foreach ($rows as $key => $item){
//            $data[$key] .= '<li><a href='."\"/Home/Novel/novelinfo/id/".$item['id']."\"><img src=\"$file_host".$item['img']."\"><p>".$item['name']."</p></a></li>";
            $data[$key] .= '<li><a href='."\"/Home/Novel/novelinfo/id/".$item['id']."\"><img src=".$item['img']."><p>".$item['name']."</p></a></li>";
        }
		$str  = implode('',$data);
		$arr['data'] = $str;
		//dump($item);
		
        $arr['status'] = 1;
        $arr['info'] = '成功';
	
        $this->ajaxReturn($arr);
    }
	
	

    /**
      *生成二维码控制器方法
      */
    public function qrcode(){
        $save_path = isset($_GET['save_path'])?$_GET['save_path']:'Public/qrcode/';  //图片存储的绝对路径
        $web_path = isset($_GET['save_path'])?$_GET['web_path']:'/Public/qrcode/';
        //查找跳转链接
        $time = date('Y-m-d',time());
        $row= D('activity')->where("type=2 and start_time <= '$time' and end_time>='$time'")->find();
        $c_url = substr($row['url'], strpos($row['url'], '/Home'));
        $zuiquan_url = 'http://qikaism.cn'.$c_url;
        //查找当前用户的的open_id
        $cur_open_id = isset($_SESSION['user']['open_id'])? $_SESSION['user']['open_id'] : $_SESSION['open_id'];
        //图片在网页上显示的路径
        $qr_data = isset($_GET['qr_data'])?$_GET['qr_data']:$zuiquan_url.'&old_openid='.$cur_open_id;

        $qr_level = isset($_GET['qr_level'])?$_GET['qr_level']:'H';
        $qr_size = isset($_GET['qr_size'])?$_GET['qr_size']:'10';
        $save_prefix = isset($_GET['save_prefix'])?$_GET['save_prefix']:'ZETA';
        if($filename = createQRcode($save_path,$qr_data,$qr_level,$qr_size,$save_prefix)){
            $pic = $web_path.$filename;
        }
        //查询在活动期间内的返回的钱

        //$money = D('activity')->where("type=2 and start_time <= '$time' and end_time>='$time'")->find();
        //dump($money);
        //dump($pic);die;
        $this->assign('pic',$pic);
        $this->assign('money',$row);
        $this->display();
        //echo "<img src='".$pic."'>";
    }


    /**
     * 搜索页面
     */
    public function search(){
        //热门搜索
        $key = $_GET['q'];
        $this->assign('key',$key);
        $this->display('search1');
    }

    /**
     * 异步搜索小说
     * */
    public function ajaxsearch(){
        //关键字
        $key = trim($_REQUEST["q"]);
        //当前页数
        $starts = $_REQUEST["p"];
        //dump($starts);
        //dump($_REQUEST["p"]);die;

        $limit = 10;
        $start = ($starts-1)*10;
        $list = D("novel")->field("id,writer,name as title,img as avatar,description as summary")->where("name like '%".$key."%' and is_shelf = 1")->limit("$start,$limit")->select();
        $total = D("novel")->where("name like '%".$key."%' and is_shelf = 1")->count();
        // 文件服务器地址
        $file_host = C('FILE_HOST_PATH');
        // 如果未搜索到数据 推荐小说
        if ($total == false && $starts == 1){
            $list = D('novel')->field("id,writer,name as title,img as avatar,description as summary")->limit(5)->order("click_count desc")->select();
            foreach($list as $item){
                $writer = empty($item['writer'])?'佚名':$item['writer'];

                $str .= '<div class="item"><a href="/Home/Novel/novelinfo/id/'.$item['id'].'"><img src="'.$file_host.$item['avatar'].'" class="avatar"><div class="body" style="height:112px;"><span class="t">'.$item['title'].'</span><span class="author">'.$writer.'</span><span
                        class="btn">立即阅读</span><p>'.$item['summary'].'</p></div></a></div>';
            }

            $strs = '<div class="title">搜索“<i class="green">'.$key.'</i>”结果，共<i class="green">0</i>条</div><div class="title">猜你喜欢：</div>'.$str;
            $no_data = '<div class="hot-box"><div class="entry">'.$strs.'</div></div>';

            $list = array("status"=>1,"data"=>$no_data,"total"=>5);
            $this->ajaxReturn($list);exit;
        }
        //第二页没有数据的情况
        if ($starts != 1 && empty($list)){
            $list = array("status"=>-21,"data"=>[],"info"=>"没有更多了111" ,'p'=>$starts);
            $this->ajaxReturn($list);exit;
        }

        $list = ["data"=>$list, "total"=>$total];
        foreach($list["data"] as $keys=>$item){
            $writer = empty($item['writer'])?'佚名':$item['writer'];
            $str .= '<div class="item"><a href="/Home/Novel/novelinfo/id/'.$item['id'].'"><img
                src="'.$file_host.$item['avatar'].'" class="avatar">
            <div class="body"><span class="t">'.$item['title'].'</span><span class="author">'.$writer.'</span><span
                    class="btn">立即阅读</span>
                <p>'.$item['summary'].'</p></div>
        </a>
        </div>';
            $list["data"][$keys]["avatar"] = C("FILE_HOST_PATH").$item["avatar"];
        }
        $res = '<div class="title">搜索“<i class="green">'.$key.'</i>”结果，共<i class="green">'.$total.'</i>条</div>';
        if ($starts == 1){
            $list['data'] = '<div class="hot-box">'.$res.'<div class="entry">'.$str.'</div></div>';
        }else{
            $list['data'] = '<div class="hot-box"><div class="entry">'.$str.'</div></div>';
        }
        $list['status'] = 1;

        $this->ajaxReturn($list);
    }

    public function test(){
        header("Content-Type: text/html; charset=UTF-8");
        $chstr="6 非法勾当之七纹铜锁伯爵篇（13）";
        $str1 = substr($chstr,0,2);
        $str2 = substr($chstr,2);
        echo $str1;
        echo "<br/>";
        echo $str2;
    }

    public function test2(){
    	foreach($_POST as $key=>$item) {
    		$data[] = $item;
    	}
    	D("test")->add($data);
    }



	//弹窗方法
	public function pop(){
        $this->is_session();
		$open_id = $_SESSION['user']['open_id'];
		$row= D('user')->where("open_id = '$open_id'")->find();
		$pop_status = $row['pop_status'];
        $data['first_view_time'] = time();
		$back_status = '';
		$day = 12*3600;
        if (date("Y-m-d",$row['first_view_time'])== date('Y-m-d',time())) {
				if($row['first_view_time'] +$day < time()){
					$row['pop_status'] = rand(1,2);
					switch ($row['pop_status']) {
						case 1:
                            $data['pop_status'] = 2;
                            $User = M("user"); // 实例化User对象
							$User->where('user_id='.$row['user_id'])->save($data); // 根据条件更新记录
							break;
						case 2:
							$data['pop_status'] = 1;
							$User = M("user"); // 实例化User对象
							$User->where('user_id='.$row['user_id'])->save($data); // 根据条件更新记录
							break;
						default:
							$data['pop_status'] = 4;
							break;
					}
            }else{
			$pop_status = 3;
			}
        }else{
			$row['pop_status'] = rand(1,2);
             switch ($row['pop_status']) {
                case 1:
                    $data['pop_status'] = 2;
					$pop_status = 2;
                    $User = M("user"); // 实例化User对象
					$User->where('user_id='.$row['user_id'])->save($data); // 根据条件更新记录
                    break;
                case 2:
                    $data['pop_status'] = 1;
					$pop_status = 1;
                    $User = M("user"); // 实例化User对象
					$User->where('user_id='.$row['user_id'])->save($data); // 根据条件更新记录
                    break;
                case 0:
                    $data['pop_status'] = 1;
					$pop_status = 1;
                    $User = M("user"); // 实例化User对象
					$User->where('user_id='.$row['user_id'])->save($data); // 根据条件更新记录
                    break;
                default:
                    $data['pop_status'] = 4;
                    break;
            }
        }
        //  2是红包,1是随机推荐,3是没有

		if( $pop_status == 2 ){
		    $pop_status = 1;
		}
		$arr = [
			'pop_status'=>$pop_status
		];
		print_r(json_encode($arr));

        // return json_encode($data);
	}


}